<template>
  <div class="center">
    <!-- 加载状态提示（可选，增强用户体验） -->
    <div v-if="loading" class="loading">数据加载中...</div>
    <!-- 错误状态提示 -->
    <div v-else-if="error" class="error">{{ error }}</div>

    <div v-else>
      <div class="up">
        <div
          class="bg-color-black item"
          v-for="(item, index) in titleItem"
          :key="item.title"
          @click="index === 14 && GotoPerCapitaWorkload()"
        >
          <p class="ml-3 colorBlue fw-b">{{ item.title }}</p>
          <div>
            <dv-digital-flop
              class="dv-dig-flop ml-1 mt-1 pl-3"
              style="text-align: center"
              :config="item.config"
            />
          </div>
        </div>
      </div>
      <div class="down">
        <div class="bg-color-black" style="width: 48%">
          <div class="d-flex pt-2 pl-2">
            <div class="d-flex">
              <span><i class="iconfont icon-tongji4" /></span>
              <span class="mx-2">在院病人概览</span>
            </div>
          </div>
          <div
            class="d-flex jc-center"
            style="width: 96%; height: 84%; margin: 10px"
          >
            <AdmissionOver />
          </div>
        </div>
        <div class="bg-color-black" style="width: 51%">
          <div class="d-flex pt-2 pl-2">
            <div class="d-flex">
              <span><i class="iconfont icon-chart-area" /></span>
              <span class="mx-2">入院病人概览</span>
            </div>
          </div>
          <div
            class="d-flex jc-center"
            style="width: 96%; height: 84%; margin-top: 10px; margin-left: 10px"
          >
            <div style="width: 93%; height: 100%" class="bg-color-black">
              <!--折线图-->
              <lineChart />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { defineComponent, reactive, onMounted, onUnmounted, ref } from "vue"; // 1. 引入onUnmounted（组件销毁钩子）
import Chart from "../center/chart/draw";
import lineChart from "./chart/lineChartView";
import AdmissionOver from "./chart/AdmissionOverview";
import axios from "axios";

export default defineComponent({
  components: {
    Chart,
    lineChart,
    AdmissionOver,
  },
  setup() {
    const titleItem = reactive([]);
    const loading = ref(true);
    const error = ref(null);

    // 2. 定义定时器引用（用于后续清除定时器）
    const refreshTimer = ref(null);

    // 水波纹图数据（无修改）
    const water = reactive({
      data: [24, 45],
      shape: "roundRect",
      formatter: "{value}%",
      waveNum: 3,
    });

    // 环形图数据（无修改）
    const rate = reactive([
      {
        id: "centerRate1",
        tips: 20,
        colorData: {
          textStyle: "#3fc0fb",
          series: {
            color: ["#00bcd44a", "transparent"],
            dataColor: {
              normal: "#03a9f4",
              shadowColor: "#97e2f5",
            },
          },
        },
      },
      {
        id: "centerRate2",
        tips: 40,
        colorData: {
          textStyle: "#67e0e3",
          series: {
            color: ["#faf3a378", "transparent"],
            dataColor: {
              normal: "#ff9800",
              shadowColor: "#fcebad",
            },
          },
        },
      },
    ]);

    // 数据请求方法（无修改）
    const fetchData = async () => {
      try {
        loading.value = true;
        const response = await axios.get(
          window.globalConfig.baseApi +
            "/api/Nurse/GetStatisticsDataJsonByName?dbKey=dbFY"
        );

        if (response.data && Array.isArray(response.data)) {
          titleItem.length = 0;
          response.data.forEach((item) => {
            const numValue = Number(item.number) || 0; // 处理空值或非数字情况
            const needDecimalTypes = ["床护比", "护患比"];
            const needDecimal = needDecimalTypes.includes(item.iiiDataType);

            titleItem.push({
              title: item.iiiDataType,
              config: {
                number: [numValue],
                // 根据条件设置toFixed属性
                ...(needDecimal && { toFixed: 1 }),
                textAlign: "left",
                content: "{nt}",
                style: {
                  fontSize: 26,
                },
              },
            });
          });
          error.value = null; // 成功时清空错误状态
        } else {
          error.value = "接口返回数据格式异常";
        }
      } catch (err) {
        console.error("获取统计数据失败:", err);
        error.value = "获取数据失败，请稍后重试";
      } finally {
        loading.value = false;
      }
    };

    // 3. 初始化与定时器管理
    onMounted(() => {
      fetchData(); // 组件挂载时先主动请求一次数据

      // 启动10分钟（600000毫秒）定时器，定时刷新数据
      const interval = 10 * 60 * 1000; // 时间换算：10分钟 = 10*60秒 = 10*60*1000毫秒
      refreshTimer.value = setInterval(() => {
        fetchData();
      }, interval);
    });

    // 4. 组件销毁前清除定时器（关键：避免内存泄漏）
    onUnmounted(() => {
      if (refreshTimer.value) {
        clearInterval(refreshTimer.value);
        console.log("定时器已清除"); // 可选：调试日志
      }
    });

    return {
      titleItem,
      water,
      rate,
      loading,
      error,
    };
  },
  methods: {
    GotoPerCapitaWorkload() {
      this.$router.push({ name: "PerCapitaWorkload" });
    },
  },
});
</script>
<style lang="scss" scoped>
/* 样式部分无修改，保持原代码 */
.center {
  width: 99%;
  height: 790px;
  display: flex;
  flex-direction: column;

  .up {
    width: 100%;
    height: 42%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;

    .item {
      border-radius: 6px;
      padding-top: 6px;
      margin-top: 8px;
      width: 23%;

      .dv-dig-flop {
        width: 150px;
        height: 30px;
      }
    }
  }

  .down {
    padding: 6px 4px;
    border-radius: 6px;
    padding-bottom: 0;
    width: 100%;
    display: flex;
    height: 56%;
    margin-top: 1%;
    justify-content: space-between;

    .bg-color-black {
      border-radius: 5px;
    }

    .ranking {
      padding: 10px;
      width: 59%;

      .dv-scr-rank-board {
        height: 220px;
      }
    }

    .percent {
      width: 40%;
      display: flex;
      flex-wrap: wrap;

      .item {
        width: 50%;
        height: 120px;

        span {
          margin-top: 8px;
          font-size: 14px;
          display: flex;
          justify-content: center;
        }
      }

      .water {
        width: 100%;

        .dv-wa-le-po {
          height: 120px;
        }
      }
    }
  }
}

.loading {
  text-align: center;
  padding: 20px;
  color: #3fc0fb;
}

.error {
  text-align: center;
  padding: 20px;
  color: #ff4d4f;
}
</style>